/*
Copyright (C) 2007 Lahiru Lakmal Priyadarshana.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,  software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or  implied.
See the License for the specific language governing permissions  and
limitations under the License.
*/

// ScreenPickerHelperObj.cpp : Implementation of CScreenPickerHelperObj

#include "stdafx.h"
#include "ScreenPickerHelperObj.h"
#include <atltypes.h>
#include <atlstr.h>


// CScreenPickerHelperObj


STDMETHODIMP CScreenPickerHelperObj::GetNumber(BSTR autocp, BSTR* message)
{
	CComBSTR return_result;

	CPoint point;
	char str[10];
	COLORREF c;
	CString strColor;
	HDC hDC;
	short r,g,b;

	static const WCHAR szDisplayW[] = { 'D','I','S','P','L','A','Y','\0' };

	hDC = CreateDC(szDisplayW,0,0,0);
	GetCursorPos(&point);
	c = GetPixel(hDC,point.x,point.y);
	r = GetRValue(c);
	g = GetGValue(c);
	b = GetBValue(c);

	//TODO: Implement Hexa
	//if (m_bHexa)
		 //sprintf(str,"%02x%02x%02x",b,g,r);
	//else 

	sprintf(str,"%02x%02x%02x",r,g,b);
	strupr(str);

	if (c == 0) strcpy(str,"000000");

	//if (m_bHexa) 
		 //strColor = "0x";
	//else 

	strColor = "#";
	strColor += str;

	char str_[12];
	for(int i=1; i<12; i++){
		str_[i]=str[i-1];
	}
	str_[0]='#';
	
	DeleteDC(hDC);

	if ( (GetAsyncKeyState(VK_F8)!=0) )
	{
	  CString csStrAutocp(autocp);

	  if (csStrAutocp=="True"){
		  if (OpenClipboard(0))
		  {
		   // Empty the Clipboard.
		   EmptyClipboard();

		   // Now let's allocate the global memory for our data.
		   HGLOBAL hClipboardData;
		   hClipboardData = GlobalAlloc(GMEM_DDESHARE, strColor.GetLength()+1);

		   // GlobalLock returns a pointer to the 
		   // data associated with the handle returned from 
		   // GlobalAlloc.
		   char * pchData;
		   pchData = (char*)GlobalLock(hClipboardData);
				  
		   // Use C/C++ strcpy function to copy the data from the local 
		   // variable to the global memory.
		   strcpy(pchData, str_);
				  
		   // Unlock the memory.
		   GlobalUnlock(hClipboardData);
				  
		   SetClipboardData(CF_TEXT,hClipboardData);
				  
		   // Close the Clipboard.
		   CloseClipboard();
		   }
	   }
	   strColor += "-1";
	}
	else
	{
	   strColor += "-0";
	}

	return_result = strColor;

	*message = return_result.Detach();

	return S_OK;
}